package com.medical.literature.visualization.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.medical.literature.visualization.entity.KeywordStatistics;
import com.medical.literature.visualization.dto.TrendItem;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 关键词统计Mapper接口
 */
@Mapper
public interface KeywordStatisticsMapper extends BaseMapper<KeywordStatistics> {
    
    /**
     * 根据条件查询关键词统计列表
     * 直接从keyword、literature_keyword和literature表中查询数据，而不是依赖keyword_statistics表
     */
    @Select("<script>" +
            "SELECT k.word as keyword, COUNT(lk.id) as count, AVG(lk.weight) as weight, k.category " +
            "FROM keyword k " +
            "JOIN literature_keyword lk ON k.id = lk.keyword_id " +
            "JOIN literature l ON lk.literature_id = l.id " +
            "WHERE l.status = 1 " +
            "<if test='userId != null'>AND l.upload_user_id = #{userId}</if> " +
            "<if test='startDate != null and startDate != \"\"'>AND l.create_time >= #{startDate}</if> " +
            "<if test='endDate != null and endDate != \"\"'>AND l.create_time &lt;= #{endDate}</if> " +
            "<if test='category != null and category != \"\"'>AND k.category = #{category}</if> " +
            "GROUP BY k.id, k.word, k.category " +
            "ORDER BY count DESC, weight DESC " +
            "<if test='limit != null and limit > 0'>LIMIT #{limit}</if>" +
            "</script>")
    List<KeywordStatistics> selectKeywordStatistics(@Param("userId") Long userId,
                                                   @Param("startDate") String startDate,
                                                   @Param("endDate") String endDate,
                                                   @Param("category") String category,
                                                   @Param("limit") Integer limit);
    
    /**
     * 查询文献趋势数据
     * 直接从literature表中查询数据，而不是依赖keyword_statistics表
     */
    @Select("<script>" +
            "SELECT DATE_FORMAT(l.create_time, '%Y-%m-%d') as timePoint, COUNT(l.id) as count " +
            "FROM literature l " +
            "WHERE l.status = 1 " +
            "<if test='userId != null'>AND l.upload_user_id = #{userId}</if> " +
            "<if test='startDate != null and startDate != \"\"'>AND l.create_time >= #{startDate}</if> " +
            "<if test='endDate != null and endDate != \"\"'>AND l.create_time &lt;= #{endDate}</if> " +
            "GROUP BY DATE_FORMAT(l.create_time, '%Y-%m-%d') " +
            "ORDER BY timePoint ASC" +
            "</script>")
    List<TrendItem> selectLiteratureTrendItems(@Param("userId") Long userId,
                                              @Param("startDate") String startDate,
                                              @Param("endDate") String endDate);
}